package com.zjh.common.datasource;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.Map;

/**
 * 动态数据源
 *
 * @author shanhuiming
 */
public class DynamicDataSource extends AbstractRoutingDataSource {

    private static final ThreadLocal<String> DATASOURCE_HOLDER = new ThreadLocal<>();

    private final Map<Object, Object> dataSourceMap;

    public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources) {
        super.setDefaultTargetDataSource(defaultTargetDataSource);
        super.setTargetDataSources(targetDataSources);
        super.afterPropertiesSet();
        this.dataSourceMap = targetDataSources;
    }

    public static String getDataSource() {
        return DATASOURCE_HOLDER.get();
    }

    public static void setDataSource(String dsType) {
        DATASOURCE_HOLDER.set(dsType);
    }

    public static void clearDataSource() {
        DATASOURCE_HOLDER.remove();
    }

    public Map<Object, Object> getDataSourceMap() {
        return dataSourceMap;
    }

    @Override
    protected Object determineCurrentLookupKey() {
        return getDataSource();
    }
}